package com.gao.config.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gao.util.JwtUtils;
import com.gao.util.WebUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gao
 * @date 2022/11/29 17:03:15
 */
@Component
public class JsonAuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = getUserDetailsFromSecurityContext();
        List<String> permissions = userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        String permissionsJson = objectMapper.writeValueAsString(permissions);
        System.out.println("permissionsJson = " + permissionsJson);
        String jwt = JwtUtils.createToken(permissionsJson, 3600);
        String responseJson = WebUtils.generateSuccessJson("认证成功", jwt);
        WebUtils.renderString(httpServletResponse, responseJson);
    }

    private UserDetails getUserDetailsFromSecurityContext() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        return userDetails;
    }

}